import java.util.*;

/**
 * @author Sebastian
 * @version 2.0
 * @date 2024/7/29 10:58
 */
// 基本计算器 II (这题不考虑括号)
    // https://leetcode.cn/problems/basic-calculator-ii/description/
    // https://labuladong.online/algo/data-structure/implement-calculator/
public class Solution227 {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<Integer>();
        int num = 0;
        char sign = '+';
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                num = num * 10 + (c - '0');
            }

            if (!Character.isDigit(c) &&  c !=' ' || i == s.length() -1) {
                if (sign == '+') {
                    stack.push(num);
                } else if (sign == '-') {
                    stack.push(-num);
                } else if (sign == '*') {
                    stack.push(stack.pop() * num);
                } else if (sign == '/') {
                    int divisor = stack.pop();
                    stack.push(divisor / num); // 注意这里只保留整数部分
                }

                num = 0;
                sign = c;
            }
        }
        int result = 0;
        while (!stack.isEmpty()) {
            result += stack.pop();
        }
        return result;
    }
}
